package com.system.dao;

import com.am.base.BaseDao;
import com.system.uitls.CommonUtil;
import com.system.uitls.IdUtils;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class ChargeDao extends BaseDao
{
  public List<Map<String, Object>> getChargeListNow(String userId, String campus)
  {
    String sql = "SELECT person_name,person_id,id,status FROM sys_patient_record WHERE (status=5 OR (status=6 AND user_id=?)) AND person_campus=?";
    return getSimpleJdbc().queryForList(sql, new Object[] { userId, campus });
  }

  public Map<String, Object> getWaitForChargePerson(String record_id, String user_id, String user_name)
  {
    Map result = null;
    String sql = null;
    try {
      sql = "SELECT status FROM sys_patient_record WHERE id=?";
      result = getSimpleJdbc().queryForMap(sql, new Object[] { record_id });

      if ("6".equals(result.get("status")))
      {
        result.put("repeat", "true");
        return result;
      }

      sql = "UPDATE sys_patient_record SET status=? WHERE id=?";
      getSimpleJdbc().update(sql, new Object[] { "6", record_id });
    }
    catch (Exception ex)
    {
      logger.info("ChargeDao[getWaitForChargePerson] sql:" + sql + "\n" + ex.getMessage());
    }
    return result;
  }

  public Map<String, String> back(String record_id, int status)
  {
    Map result = new HashMap();
    String sql = null;
    int diagnose = getSimpleJdbc().queryForInt("SELECT count(*) FROM sys_diagnose  WHERE record_id=?", new Object[] { record_id });
    int dressing = getSimpleJdbc().queryForInt("SELECT count(*) FROM sys_dressing  WHERE record_id=?", new Object[] { record_id });
    int inject = getSimpleJdbc().queryForInt("SELECT count(*) FROM sys_prescription t,sys_diagnose t1 WHERE t1.id=t.diagnose_id AND t.type='2' AND t1.record_id=?", new Object[] { record_id });
    if ((diagnose > 0) && (dressing == 0) && (inject == 0))
      status = 2;
    try
    {
      sql = "UPDATE sys_patient_record SET status=? WHERE id=?";
      getSimpleJdbc().update(sql, new Object[] { Integer.valueOf(status), record_id });
      result.put("type", "success");
      result.put("value", "返回成功");
    }
    catch (Exception ex) {
      logger.info("ChargeDao[back] sql:" + sql + "\n" + ex.getMessage());
      result.put("type", "fail");
      result.put("value", "返回失败");
    }
    return result;
  }

  public Map<String, String> chargeSubmit(Map<String, Object> map)
  {
    String record_id = CommonUtil.nullToEmptyString(map.get("record_id"));
    String currentUserId = CommonUtil.nullToEmptyString(map.get("currentUserId"));
    String currentUserName = CommonUtil.nullToEmptyString(map.get("currentUserName"));
    String currentUserCampus = CommonUtil.nullToEmptyString(map.get("currentUserCampus"));

    Map result = new HashMap();
    List sqlList = new ArrayList();
    List params = new ArrayList();
    try
    {
      String dressing_amount = CommonUtil.nullToEmptyString(map.get("dressing_amount"));
      if (dressing_amount != "") {
        String infuse_amount = CommonUtil.nullToEmptyString(map.get("infuse_amount"));
        String laboratory_amount = CommonUtil.nullToEmptyString(map.get("laboratory_amount"));
        double privatePay = Float.parseFloat(CommonUtil.nullToEmptyString(map.get("privatePay")));
        double publicPay = Float.parseFloat(CommonUtil.nullToEmptyString(map.get("publicPay")));
        int percentage = CommonUtil.convertToInt(CommonUtil.nullToEmptyString(map.get("percentage")), 100);

        double drug_amount_fact = Math.round((privatePay + publicPay * percentage / 100.0D) * 100.0D) / 100.0D;

        double drug_amount = privatePay + publicPay;

        String receivable_total = CommonUtil.nullToEmptyString(map.get("receivable_total"));

        String fact_total = CommonUtil.nullToEmptyString(map.get("fact_total"));
        sqlList.add("update sys_patient_record set status=?,dressing_amount=?,infuse_amount=?,laboratory_amount=?,drug_amount_fact=?,drug_amount=?,percentage=?,receivable_total=?,amount=? WHERE id=?");
        params.add(new Object[] { "7", dressing_amount, infuse_amount, laboratory_amount, Double.valueOf(drug_amount_fact), Double.valueOf(drug_amount), Integer.valueOf(percentage), receivable_total, fact_total, record_id });
      } else {
        sqlList.add("UPDATE sys_patient_record SET status=? WHERE id=?");
        params.add(new Object[] { "7", record_id });
      }

      String out_storage_id = IdUtils.getSequence(getJdbc(), "sys_out_storage_id");
      sqlList.add("insert into sys_out_storage(id,create_time,user_id,user_name,place,campus) values(?,?,?,?,?,?)");
      params.add(new Object[] { out_storage_id, CommonUtil.getCurDate(), currentUserId, currentUserName, "0", currentUserCampus });

      List<Map<String, Object>> drugList = getSimpleJdbc().queryForList("select t1.drug_id,(SELECT drugstore_num FROM sys_drug t where t.id=t1.drug_id) as drugstore_num,t1.quantity from sys_prescription t1,sys_diagnose t2,sys_patient_record t3 where t1.diagnose_id=t2.id AND t2.record_id=t3.id AND t3.id=?", new Object[] { record_id });

      for (Map obj : drugList)
      {
        String drugstore_num = CommonUtil.nullToEmptyString(obj.get("drugstore_num"));

        String drug_id = CommonUtil.nullToEmptyString(obj.get("drug_id"));
        String quantity = CommonUtil.nullToEmptyString(obj.get("quantity"));

        if (Integer.parseInt(drugstore_num) < Integer.parseInt(quantity))
        {
          result.put("type", "repeat");
          result.put("value", "药品库存不足");
          return result;
        }
        sqlList.add("update sys_drug set drugstore_num=drugstore_num-? where id=?");
        params.add(new Object[] { quantity, drug_id });

        String histroy_id = IdUtils.getSequence(getJdbc(), "sys_drug_history_id");
        sqlList.add("insert into sys_drug_history(id,drug_id,quantity,status,type,out_storage_id) values(?,?,?,?,?,?)");
        params.add(new Object[] { histroy_id, drug_id, quantity, "1", "6", out_storage_id });
      }

      batchInTransaction(sqlList, params);
      result.put("type", "success");
      result.put("value", "提交成功");
    }
    catch (Exception ex) {
      logger.info("DoctorDao[submit]-->收费提交失败" + ex.getMessage());
      result.put("type", "fail");
      result.put("value", "提交失败");
    }
    return result;
  }

  public Map<String, Object> getChargeInfo(String record_id)
  {
    Map result = null;
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(1);
    try {
      result = getSimpleJdbc().queryForMap("SELECT name,sex,amount,t1.type,telephone,class,address,id_card,is_overdue,(SELECT percentage FROM sys_cost_definition t WHERE person_type=t1.type AND t.register_type=t2.register_type) as percentage FROM sys_person t1,sys_patient_record t2 WHERE t1.id=t2.person_id AND t2.id=?", new Object[] { record_id });
      result.put("myamount", result.get("amount"));
      String is_overdue = CommonUtil.nullToEmptyString(result.get("is_overdue"));
      if ("1".equals(is_overdue))
      {
        result.put("percentage", "100");
      }
      result.putAll(getSimpleJdbc().queryForMap("SELECT isnull(t2.dressing_amount,0) as dressing_amount,isnull(t2.infuse_amount,0) as infuse_amount,isnull(t2.laboratory_amount,0) as laboratory_amount,t2.amount,name,sex,t1.type,card_num,telephone,user_name,class,address,id_card FROM sys_person t1,sys_patient_record t2 WHERE t1.id=t2.person_id AND t2.id=?", new Object[] { record_id }));
      result.putAll(getSimpleJdbc().queryForMap("SELECT count(1) as times,isnull(sum(amount),0) as amount,convert(char(4),max(create_time)) as last_time FROM sys_person t1,sys_patient_record t2 WHERE t1.id=t2.person_id AND DATEPART(yyyy,create_time)=?", new Object[] { Integer.valueOf(year) }));

      result.putAll(getSimpleJdbc().queryForMap("SELECT isnull(sum(t1.amount),0) as publicPay FROM sys_prescription t1,sys_drug t2,sys_diagnose t3 WHERE t1.drug_id=t2.id AND t2.is_own='1' AND t3.record_id=? AND t1.diagnose_id=t3.id", new Object[] { record_id }));

      result.putAll(getSimpleJdbc().queryForMap("SELECT isnull(sum(t1.amount),0) as privatePay FROM sys_prescription t1,sys_drug t2,sys_diagnose t3 WHERE t1.drug_id=t2.id AND t2.is_own='0' AND t3.record_id=? AND t1.diagnose_id=t3.id", new Object[] { record_id }));
      result.put("currentDate", CommonUtil.getFormatCurDate("yyyy年MM月dd日"));
      result.put("number", new DoctorDao().getNumber());
    } catch (Exception ex) {
      result = new HashMap();
      logger.error("ChargeDao[getChargeInfo]-->查询收费信息出错\n" + ex.getMessage());
    }

    return result;
  }
}